<template>
  <van-cell-group>
    <van-field
      v-model="phone"
      label="手机号"
      placeholder="请输入手机号"
      left-icon="contact"
      error-message=""
    />
    <van-field
      v-model="sms"
      center
      clearable
      label="验证码"
      placeholder="请输入短信验证码"
      left-icon="chat"
    >
      <van-button slot="button" size="small" type="primary" @click="getCode">发送验证码</van-button>
    </van-field>
    <van-field
      v-model="password"
      type="password"
      label="密码"
      placeholder="请输入密码"
      required
      left-icon="lock"
    />
    <div class="register_submit">
      <van-button size="large" type="danger" @click="submit">注册</van-button>
    </div>

    <div class="register_footer">
      已有账号?
      <router-link to="/login" class="red">登录</router-link>
    </div>
  </van-cell-group>
</template>

<script>
import { Popup, Field, CellGroup, Button, Toast } from 'vant'

export default {
  data () {
    return {
      phone: '',
      sms: '',
      password: '',
      verificationId: null
    }
  },

  methods: {
    async getCode () {
      const params = { 'receiver': this.phone, 'recaptcha_response': true }
      const { data } = await this.$api.account.verificationCreate(params)
      console.log(data)
      if (data.code !== 200) {
        throw new Error(data.desc)
      }
      this.verificationId = data.data.id
    },
    async submit () {
      let sourceId = this.$route.query.source_id || 0
      let sourceType = this.$route.query.source_type || 0
      console.log(sourceId)
      console.log(sourceType)
      const params = {
        'verification_id': this.verificationId,
        'code': this.sms,
        'username': this.phone,
        'password': this.password,
        'source_type': sourceType,
        'source_id': sourceId
      }
      console.log(params)
      const { data } = await this.$api.account.userCreate(params)
      console.log(data)
      if (data.code !== 200) {
        Toast(data.desc)
        return
      }
      Toast('注册成功')
      this.$router.push({ name: 'login' })
    }
  },

  components: {
    [Field.name]: Field,
    [CellGroup.name]: CellGroup,
    [Button.name]: Button,
    [Popup.name]: Popup
  }
}
</script>

<style scoped>

</style>
